package net.retorx.jai

import java.io.File
import net.retorx.util.ImageUtil._
import scala.actors.Futures._


object ImageFileManager {

	def getScaledFileSuffix() = "-scaled.png"
	def getGrayscaleThumbnailFileSuffix() = "-gray-thumb.png"
	def getThumbnailFileSuffix() = "-thumb.png"

	def buildThumbnails(file: File, thumbnailFile: File, grayscaleThumbnailFile: File) = {
		future {
			val thumbnailImage = createThumbnailImage(file)
			val grayscaleThumbnailImage = desaturateImage(thumbnailImage)

			savePNGImageFile(thumbnailFile, thumbnailImage)
			savePNGImageFile(grayscaleThumbnailFile, grayscaleThumbnailImage)
			System.out.println("done building a scaled image!")
		}

		(thumbnailFile, grayscaleThumbnailFile)
	}

	private def createThumbnailImage(file: File) = {
		val renderedImage = createBufferedImage(file)
		resizeImage(renderedImage, 100, 100)
	}

	def getThumbnailFiles(file: File) = {
		val grayscaleThumbnailFile = getGrayscaleThumbnailFile(file)
		val thumbnailFile = getThumbnailFile(file)

		(thumbnailFile, grayscaleThumbnailFile)
	}

	def getGrayscaleThumbnailFile(file: File) = {
		val thumbFileName = createFilenameWithSuffix(file, getGrayscaleThumbnailFileSuffix())
		new File(file.getParentFile, thumbFileName)
	}

	def getThumbnailFile(file: File) = {
		val thumbFileName = createFilenameWithSuffix(file, getThumbnailFileSuffix())
		new File(file.getParentFile, thumbFileName)
	}

	private def createFilenameWithSuffix(file: File, suffix: String) = {
		file.getName.substring(0, file.getName.lastIndexOf(".")) + suffix
	}

	def buildScaledImageFile(scaledImageFile: File, originalFile: File) {
		val renderedImage = createBufferedImage(originalFile)
		val scaledImage = resizeConstrainedScaledImage(renderedImage, 1200, 1200)
		savePNGImageFile(scaledImageFile, scaledImage)
	}
}
